package com.LeeCode;

import java.util.Arrays;

/**
 * 半径为 k 的子数组平均值
 */

public class Code2090 {
    public static void main(String[] args) {
        int[] nums = {7, 4, 3, 9, 1, 8, 5, 2, 6};
        System.out.println(Arrays.toString(new Code2090().getAverages(nums, 3)));

    }

    public int[] getAverages(int[] nums, int k) {
        int n = nums.length;
        int[] ans = new int[n];
        Arrays.fill(ans, -1);

        int windowSize = 2 * k + 1;
        if (windowSize > n) {
            return ans;
        }

        long sum = 0; // 使用long防止溢出
        for (int i = 0; i < windowSize; i++) {
            sum += nums[i];
        }

        ans[k] = (int) (sum / windowSize); // 先计算第一个窗口

        for (int i = k + 1; i < n - k; i++) {
            sum += nums[i + k] - nums[i - k - 1]; // 修正边界
            ans[i] = (int) (sum / windowSize);
        }

        return ans;
    }
}
